import SwiftUI
import Network
import Combine

struct ConnectionView: View {
    @EnvironmentObject var connectionSettings: ConnectionSettings
    @EnvironmentObject var tcpCarService: TCPCarService
    @EnvironmentObject var appSettings: AppSettings
    @State private var showAlert = false
    @State private var alertMessage = ""
    @State private var isConnected = false
    
    var body: some View {
        NavigationView {
            ScrollView {
                VStack(spacing: 25) {
                    // 标题和图标
                    VStack(spacing: 15) {
                        Image(systemName: "car.fill")
                            .font(.system(size: 60))
                            .foregroundColor(.blue)
                        
                        Text("智能小车控制系统")
                            .font(.largeTitle)
                            .fontWeight(.bold)
                        
                        Text("请输入小车TCP连接信息")
                            .font(.subheadline)
                            .foregroundColor(.secondary)
                    }
                    .padding(.top, 50)
                    
                    // 连接表单
                    VStack(spacing: 20) {
                        // 调试模式开关
                        Toggle(isOn: $appSettings.isDebugMode.onChange { newValue in
                            // 当调试模式状态改变时，通知TCPCarService
                            tcpCarService.setDebugMode(newValue)
                        }) {
                            HStack {
                                Image(systemName: "ladybug")
                                    .foregroundColor(.orange)
                                Text("调试模式")
                                    .font(.headline)
                            }
                        }
                        .padding()
                        .background(Color(.systemGray6))
                        .cornerRadius(10)
                        
                        if appSettings.isDebugMode {
                            Text("调试模式已开启，无需TCP连接即可进入应用")
                                .font(.caption)
                                .foregroundColor(.orange)
                                .padding(.horizontal)
                        }
                        
                        // IP地址输入
                        VStack(alignment: .leading, spacing: 8) {
                            Text("小车IP地址")
                                .font(.headline)
                            
                            TextField("例如：192.168.1.100", text: $connectionSettings.ipAddress)
                                .padding()
                                .background(Color(.systemGray6))
                                .cornerRadius(10)
                                .keyboardType(.decimalPad)
                                .disabled(appSettings.isDebugMode)
                                .opacity(appSettings.isDebugMode ? 0.6 : 1.0)
                        }
                        
                        // 端口输入
                        VStack(alignment: .leading, spacing: 8) {
                            Text("控制端口")
                                .font(.headline)
                            
                            TextField("例如：8080", text: $connectionSettings.port)
                                .padding()
                                .background(Color(.systemGray6))
                                .cornerRadius(10)
                                .keyboardType(.numberPad)
                                .disabled(appSettings.isDebugMode)
                                .opacity(appSettings.isDebugMode ? 0.6 : 1.0)
                        }
                        
                        // 摄像头端口输入
                        VStack(alignment: .leading, spacing: 8) {
                            Text("摄像头端口")
                                .font(.headline)
                            
                            TextField("例如：8081", text: $connectionSettings.cameraPort)
                                .padding()
                                .background(Color(.systemGray6))
                                .cornerRadius(10)
                                .keyboardType(.numberPad)
                                .disabled(appSettings.isDebugMode)
                                .opacity(appSettings.isDebugMode ? 0.6 : 1.0)
                        }
                        
                        // 错误信息显示
                        if !appSettings.isDebugMode, let errorMessage = tcpCarService.connectionError ?? connectionSettings.connectionError {
                            Text(errorMessage)
                                .foregroundColor(.red)
                                .padding(.vertical, 8)
                                .animation(.easeInOut, value: tcpCarService.connectionError)
                        }
                    }
                    .padding(.horizontal)
                    
                    // 连接按钮
                    NavigationLink(
                        destination: ContentView()
                            .navigationBarBackButtonHidden(true),
                        isActive: $isConnected,
                        label: {
                            Button(action: {
                                if appSettings.isDebugMode {
                                    // 调试模式下直接进入
                                    isConnected = true
                                } else {
                                    // 正常模式下连接TCP
                                    connectToCar()
                                }
                            }) {
                                HStack {
                                    if tcpCarService.isConnecting && !appSettings.isDebugMode {
                                        ProgressView()
                                            .progressViewStyle(CircularProgressViewStyle(tint: .white))
                                            .padding(.trailing, 10)
                                    }
                                    
                                    Text(appSettings.isDebugMode ? "进入应用（调试模式）" : 
                                         tcpCarService.isConnecting ? "TCP连接中..." : "连接到小车")
                                        .fontWeight(.bold)
                                }
                                .frame(maxWidth: .infinity)
                                .padding()
                                .background(appSettings.isDebugMode ? Color.orange : 
                                           tcpCarService.isConnecting ? Color.gray : Color.blue)
                                .foregroundColor(.white)
                                .cornerRadius(15)
                                .padding(.horizontal, 20)
                            }
                            .disabled(tcpCarService.isConnecting && !appSettings.isDebugMode)
                        }
                    )
                    .padding(.bottom, 30)
                }
            }
            .navigationBarHidden(true)
            .padding()
        }
        .alert(isPresented: $showAlert) {
            Alert(title: Text("连接错误"), message: Text(alertMessage), dismissButton: .default(Text("确定")))
        }
        // 监听连接状态变化
        .onReceive(tcpCarService.$isConnected) { connected in
            if connected {
                isConnected = true
            }
        }
        .onAppear {
            // 页面出现时，设置TCPCarService的调试模式
            tcpCarService.setDebugMode(appSettings.isDebugMode)
        }
    }
    
    // 连接到小车
    private func connectToCar() {
        // 如果是调试模式，直接进入
        if appSettings.isDebugMode {
            isConnected = true
            return
        }
        
        // 验证IP地址和端口格式
        guard isValidIPAddress(connectionSettings.ipAddress) else {
            connectionSettings.connectionError = "IP地址格式不正确"
            alertMessage = connectionSettings.connectionError!
            showAlert = true
            return
        }
        
        // 更新TCP服务的连接设置
        tcpCarService.updateConnectionSettings(connectionSettings)
        
        // 开始TCP连接
        tcpCarService.connect { success in
            if success {
                // 连接成功，进入主界面
                isConnected = true
            } else {
                // 连接失败，显示错误
                if let errorMessage = tcpCarService.connectionError {
                    alertMessage = errorMessage
                    showAlert = true
                } else {
                    alertMessage = "连接失败，请检查网络设置"
                    showAlert = true
                }
            }
        }
    }
    
    // 验证IP地址格式
    private func isValidIPAddress(_ ip: String) -> Bool {
        let parts = ip.split(separator: ".")
        guard parts.count == 4 else { return false }
        
        for part in parts {
            guard let num = Int(part), num >= 0 && num <= 255 else {
                return false
            }
        }
        return true
    }
}

// 添加 Published 属性绑定变更的扩展
extension Published.Publisher where Value: Equatable {
    func onChange(_ handler: @escaping (Value) -> Void) -> AnyPublisher<Value, Never> {
        self.removeDuplicates()
            .dropFirst()
            .handleEvents(receiveOutput: handler)
            .eraseToAnyPublisher()
    }
}

extension Binding {
    func onChange(_ handler: @escaping (Value) -> Void) -> Binding<Value> {
        Binding(
            get: { self.wrappedValue },
            set: { newValue in
                self.wrappedValue = newValue
                handler(newValue)
            }
        )
    }
}

struct ConnectionView_Previews: PreviewProvider {
    static var previews: some View {
        ConnectionView()
            .environmentObject(ConnectionSettings())
            .environmentObject(TCPCarService())
            .environmentObject(AppSettings())
    }
} 